package org.gaelocaltest.ext;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author 403rus@gmail.com (Dmitriy T.)
 */
public class ServletRunner {

	public static void runMockServlet(HttpServlet servInstance, MockHttpServletRequest request,
			MockHttpServletResponse response) throws Exception {
		Method meth;
		Class partypes[] = new Class[2];
		partypes[0] = HttpServletRequest.class;
		partypes[1] = HttpServletResponse.class;

		if (request.getMethod().equalsIgnoreCase("POST")) {
			meth = servInstance.getClass().getMethod("doPost", partypes);
		} else if (request.getMethod().equalsIgnoreCase("GET")) {
			meth = servInstance.getClass().getMethod("doGet", partypes);
		} else
			throw (new Exception("Unknown method type"));

		try {
			meth.invoke(servInstance, HttpServletRequest.class.cast(request),
					HttpServletResponse.class.cast(response));
		} catch (InvocationTargetException e) {
			response.setStatus(500);
		}

	}
}
